package com.smart.list.analizer.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;



/**
 * @author dninkovi
 *	Lucene implementation of Analyzer
 */
public class TextAnalyzerLuceneImpl implements com.smart.list.analizer.TextAnalyzer {
	Logger logger = Logger.getAnonymousLogger();
	private Analyzer analyzer;
	private Directory index;


	public TextAnalyzerLuceneImpl() {
		super();
		analyzer = new StandardAnalyzer(Version.LUCENE_31);
		index = new RAMDirectory();
	}

	public List<String> getCategories(String taskArg, Long id, List<String> context) {
		
		List<String> categories = new ArrayList<String>();	
		
	    addDoc(taskArg, id);	
		
		for(String category : context){
			try {
				IndexSearcher isearcher = new IndexSearcher(index, true);
				StringBuilder queryStr = new StringBuilder();
				//queryStr.append("task:").append("\"").append(category).append("\"").append("~");
				queryStr.append("task:").append(category).append("~0.4");
				QueryParser parser = new QueryParser(Version.LUCENE_31,"task", analyzer);
				Query query = parser.parse(queryStr.toString());
				logger.info(queryStr.toString());
				ScoreDoc[] hits = isearcher.search(query, null, 1000).scoreDocs;

				for (int i = 0; i < hits.length; i++) {
					Document hitDoc = isearcher.doc(hits[i].doc);
					categories.add(hitDoc.get("id"));
				}
				
				isearcher.close();
				logger.info("Searched: " + categories);
			} catch (CorruptIndexException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
			} 
		}

		return categories;
	}
	
	
	private void addDoc(String taskArg, Long id){
		 IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_31, analyzer);

		    try {
				IndexWriter w = new IndexWriter(index, config);		   
				Document doc = new Document();
			    doc.add(new Field("task", taskArg, Field.Store.YES, Field.Index.ANALYZED));
			    doc.add(new Field("id", id.toString(), Field.Store.YES, Field.Index.ANALYZED));
			    w.addDocument(doc);
				w.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}


}
